package com.aurora.source.source.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aurora.source.R;
import com.aurora.source.authority.presenter.ExaminePresenter;
import com.aurora.source.authority.view.IExamineView;
import com.aurora.source.base.BaseWhiteToolbarActivity;
import com.aurora.source.base.WebViewActivity;
import com.aurora.source.center.activity.SourceCenterMainActivity;
import com.aurora.source.entity.SysPermissionEntity;
import com.aurora.source.entity.UserEntity;
import com.aurora.source.event.EventData;
import com.aurora.source.greendao.SysPermissionEntityDao;
import com.aurora.source.source.bean.UserInfoBean;
import com.aurora.source.source.presenter.PortraitPresenter;
import com.aurora.source.source.view.IPortraitView;
import com.aurora.source.util.GreenDaoHelper;
import com.aurora.source.util.SPUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 设置
 */
public class SettingActivity extends BaseWhiteToolbarActivity<PortraitPresenter> implements IPortraitView, IExamineView {

    @BindView(R.id.iv_portrait)
    ImageView ivPortrait;
    @BindView(R.id.ll_change_password)
    LinearLayout llChangePassword;
    @BindView(R.id.ll_phone)
    LinearLayout llPhone;
    @BindView(R.id.ll_clear_cache)
    LinearLayout llClearCache;
    @BindView(R.id.tv_exit)
    TextView tvExit;
    @BindView(R.id.iv_home)
    ImageView ivHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.ll_home)
    LinearLayout llHome;
    @BindView(R.id.iv_source)
    ImageView ivSource;
    @BindView(R.id.tv_source)
    TextView tvSource;
    @BindView(R.id.ll_source)
    LinearLayout llSource;
    @BindView(R.id.iv_setting)
    ImageView ivSetting;
    @BindView(R.id.tv_setting)
    TextView tvSetting;
    @BindView(R.id.ll_setting)
    LinearLayout llSetting;
    ExaminePresenter examinePresenter;
    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;

    @Override
    public PortraitPresenter attach() {
        examinePresenter = new ExaminePresenter(this);
        return new PortraitPresenter(this);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_setting;
    }

    @Override
    public void initData(@Nullable Bundle bundle) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshUI();
    }

    private void refreshUI() {
        UserEntity userEntity = GreenDaoHelper.getDaoSession().getUserEntityDao().loadAll().get(0);
        if (userEntity != null) {
            Glide.with(this)
                    .load(userEntity.getUserHeadPath())
                    .apply(new RequestOptions().placeholder(R.drawable.ico_txiang01))
                    .into(ivPortrait);
        }
    }

    @Override
    public void initView(Bundle savedInstanceState, View contentView) {
        refresh.setEnableOverScrollDrag(true);
        refresh.setEnableOverScrollBounce(true);
        refresh.setEnableLoadMore(false);
        refresh.setEnableRefresh(false);
        refresh.setReboundDuration(1000);
        simpleToolbar.setMainTitle("设置");
        simpleToolbar.setLeftVisibility(View.VISIBLE);
        tvSetting.setTextColor(Color.parseColor("#5DD189"));
        ivSetting.setImageResource(R.drawable.ico_nav_sz1);
    }

    @Override
    public void doBusiness() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    // 打开相册/拍照
    public void showPictureSelector(int MaxSelect, boolean isCrop) {
        try {
            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(MaxSelect)// 最大图片选择数量 int
                    .minSelectNum(1)// 最小选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                    .withAspectRatio(1, 1)
                    .imageFormat(PictureMimeType.JPEG)// 拍照保存图片格式后缀,默认jpeg
                    .setOutputCameraPath(application.getFilesDir().getAbsolutePath())// 自定义拍照保存路径,可不填
                    .enableCrop(isCrop)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                    .compressSavePath(application.getFilesDir().getAbsolutePath())//压缩图片保存地址
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                    .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                    .openClickSound(true)// 是否开启点击声音 true or false
                    .cropCompressQuality(80)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    File file = new File(selectList.get(0).getCutPath());
                   /* Glide.with(this)
                            .load(file)
                            .into(ivPortrait);*/
                    Map<String, String> params = new HashMap<>();
                    params.put("userId", (String) SPUtils.get(activity, SPUtils.USER_ID, ""));
                    basePresenter.portrait(activity, file, params);
                    break;

            }
        }
    }

    @OnClick({R.id.ll_home, R.id.ll_source, R.id.iv_portrait, R.id.ll_change_password, R.id.ll_phone, R.id.ll_clear_cache, R.id.tv_exit, R.id.ll_privacy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_home:
                hideSoftInput();
                finish();
                break;
            case R.id.ll_source:
                hideSoftInput();
                gotoActivity(SourceCenterMainActivity.class, true);
                break;
            case R.id.iv_portrait:
                showPictureSelector(1, true);//添加图片
                break;
            case R.id.ll_change_password:
                gotoActivity(SmsVerificationActivity.class, false);
                break;
            case R.id.ll_phone:
                gotoActivity(RevampMobileActivity.class, false);
                break;
            case R.id.ll_clear_cache:
                PictureFileUtils.deleteCacheDirFile(SettingActivity.this);//清除图片选择器
                clearImageAllCache(SettingActivity.this);
                showToast("缓存清除成功！");
                break;
            case R.id.tv_exit:
                EventBus.getDefault().post(EventData.logOut);
                hideSoftInput();
                finish();
                break;
            case R.id.ll_privacy:
                Bundle bundle = new Bundle();
                bundle.putString("title","区块链溯源系统隐私政策");
                bundle.putString("url","https://iic.api.aoruola.net.cn/iic-api-front/h5/article/articleDetail.html?classCode=setting_protocol_declare&title=区块链溯源系统隐私政策");
                gotoActivity(WebViewActivity.class,false,bundle);
                break;
        }
    }


    /**
     * 清除图片所有缓存
     */
    public void clearImageAllCache(Context context) {
        clearImageDiskCache(context);
        clearImageMemoryCache(context);
        String ImageExternalCatchDir = context.getExternalCacheDir() + ExternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR;
        deleteFolderFile(ImageExternalCatchDir, true);
    }


    /*** 清除图片磁盘缓存 */
    public void clearImageDiskCache(final Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(context).clearDiskCache();
                        //BusUtil.getBus().post(new GlideCacheClearSuccessEvent());
                    }
                }).start();
            } else {
                Glide.get(context).clearDiskCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*** 清除图片内存缓存*/
    public void clearImageMemoryCache(Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                //只能在主线程执行
                Glide.get(context).clearMemory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*** 删除指定目录下的文件，这里用于缓存的删除
     *** @param filePath filePath
     ** @param deleteThisPath deleteThisPath
     **/
    private void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    for (File file1 : files) {
                        deleteFolderFile(file1.getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {
                        file.delete();
                    } else {
                        if (file.listFiles().length == 0) {
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onPortraitSuccess(String msg) {
        showToast(msg);
        Map<String, String> params = new HashMap<>();
        params.put("userId", userId);
        examinePresenter.Examine(activity, params, false);
    }

    @Override
    public void onPortraitFail(String msg) {
        showToast(msg);
    }

    @Override
    public void onExamineSuccess(UserInfoBean data) {
        //保存用户信息
        UserEntity userEntity = GreenDaoHelper.getDaoSession().getUserEntityDao().loadAll().get(0);
        String pwd = userEntity.getUserPwd();
        Long id = userEntity.getId();
        data.getUserInfoDTO().setUserPwd(pwd);
        data.getUserInfoDTO().setId(id);
        GreenDaoHelper.getDaoSession().getUserEntityDao().insertOrReplace(data.getUserInfoDTO());
        //保存权限信息
        SysPermissionEntity sysPermissionEntity1 = GreenDaoHelper.getDaoSession().getSysPermissionEntityDao().queryBuilder().where(SysPermissionEntityDao.Properties.UserId.eq(userEntity.getUserId())).unique();
        List<String> sysRoleList = data.getUserInfoDTO().getSysRoleList();//权限列表
        if(sysRoleList!=null&&sysRoleList.size()>0){
            //ADD_USER,ADD_BATCH,ADD_LOGISTICS,UPDATE_COMPANY,ADD_PRODUCT
            if(sysRoleList.contains("ADD_USER")){ //添加子账号
                sysPermissionEntity1.setAddUser(true);
            }else {
                sysPermissionEntity1.setAddUser(false);
            }
            if(sysRoleList.contains("ADD_BATCH")){ //添加批次
                sysPermissionEntity1.setAddBatch(true);
            }else {
                sysPermissionEntity1.setAddBatch(false);
            }
            if(sysRoleList.contains("ADD_LOGISTICS")){ //添加物流
                sysPermissionEntity1.setAddLogistics(true);
            }else {
                sysPermissionEntity1.setAddLogistics(false);
            }
            if(sysRoleList.contains("UPDATE_COMPANY")){ //修改公司
                sysPermissionEntity1.setUpdateCompany(true);
            }else {
                sysPermissionEntity1.setUpdateCompany(false);
            }
            if(sysRoleList.contains("ADD_PRODUCT")){ //添加商品
                sysPermissionEntity1.setAddProduct(true);
            }else {
                sysPermissionEntity1.setAddProduct(false);
            }
        }else {
            sysPermissionEntity1.setAddUser(false);
            sysPermissionEntity1.setAddBatch(false);
            sysPermissionEntity1.setAddLogistics(false);
            sysPermissionEntity1.setUpdateCompany(false);
            sysPermissionEntity1.setAddProduct(false);
        }
        //插入权限信息
        GreenDaoHelper.getDaoSession().getSysPermissionEntityDao().insertOrReplace(sysPermissionEntity1);
        refreshUI();//更新UI
    }

    @Override
    public void onExamineFail(String msg) {
        showToast(msg);
    }
}
